/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: syyyy
 * Date: 2025-09-20
 * Time: 15:25
 */
public class HashBuck2<K,V> {
    static class Node<K,V>{
        public K key;
        public V val;
        public Node<K,V> next;

        public Node(K key,V val){
            this.key=key;
            this.val=val;
        }
    }

    public Node<K,V>[] array = (Node<K,V>[])new Node[10];//为什么这里要强制转换？  因为擦除机制，数组变成<Object,Object>,所以强制转换一下
    public int usedSize;

    public static final double DEFAULT_LOAD_FACTOR = 0.75f;

    public void push(K key,V val){
        //假如这里是引用类型的K，就不能单纯用前面那个哈希函数得到下标了
        int hashCode=key.hashCode();
        int index=hashCode % array.length;
        Node<K,V> cur=array[index];
        while(cur != null){
            if(cur.key.equals(key)){
                cur.val=val;
                return;
            }
            cur=cur.next;
        }
        //如果找到相同的key，就要插入
        Node<K,V> node=new Node<>(key,val);
        node.next=array[index];
        array[index]=node;
        usedSize++;

        if (isFull()) {
            resize();
        }
    }
    private void resize(){
        Node<K,V>[] newArray=(Node<K, V>[])new Node[10];
        for (int i = 0; i < array.length; i++) {
            Node<K,V> cur=array[i];
            while (cur != null){
                Node<K,V> curN=cur.next;
                int newIndex= cur.key.hashCode() % newArray.length;
                //依旧头插法
                cur.next=newArray[newIndex];
                newArray[newIndex]=cur;
                cur=curN;
            }
        }
        array=newArray;
    }
    private boolean isFull() {
        return usedSize*1.0/ array.length >= DEFAULT_LOAD_FACTOR;
    }
}
